package juc_learn.threadSignal;

import java.util.concurrent.TimeUnit;

/**
 *先打印5次“printA…”，再打印5次“printB…”，每次打印间隔1秒，重复循环2次
 * @author wangshuo2
 *
 */
class MyService {
	private volatile  boolean flag = false; 
	public   synchronized void printA(){
		try{
			while(flag){
		
			wait();
		  }
		  for(int i=0;i<5;i++){
			  System.out.println("A");
			  TimeUnit.SECONDS.sleep(1);
			  
		  }
		  flag = true;
		  notifyAll();
		} catch(Exception e){
	    	e.printStackTrace();
	    }
	}
	
	public  synchronized void printB(){
		try{
			while(!flag){
				wait();
			}
			for(int i=0;i<5;i++){
				  System.out.println("B");
				  TimeUnit.SECONDS.sleep(1);
				  
			  }
			flag = false;
			notifyAll();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}


class ThreadA implements Runnable{
    private MyService ocp;
    public ThreadA(MyService ocp){
    	this.ocp = ocp;
    }
    
    
	@Override
	public void run() {
		// TODO Auto-generated method stub
		ocp.printA();
	}
	
}


class ThreadB implements Runnable{
    private MyService ocp;
    public ThreadB(MyService ocp){
    	this.ocp = ocp;
    }
    
    
	@Override
	public void run() {
		// TODO Auto-generated method stub
		ocp.printB();
	}
	
}

public class OrderCrossPrint_syn {
	
	public static void main(String[] args) {
		MyService ms = new MyService();
	     for(int i=0;i<2;i++){
	    	new Thread(new ThreadA(ms)).start();
	    	new Thread(new ThreadB(ms)).start();
	     }
	}

}
